from app.models import db, SceneStep

def create_steps(scene_id, steps, parent_id=None, order_offset=0):
    """递归创建场景步骤"""
    for i, step_data in enumerate(steps):
        step = SceneStep(
            scene_id=scene_id,
            parent_id=parent_id,
            api_id=step_data.get('api_id'),
            type=step_data.get('type', 'api'),
            name=step_data.get('name', ''),
            order=order_offset + i,
            config=step_data.get('config', {})
        )
        
        db.session.add(step)
        db.session.flush()  # 获取步骤ID
        
        # 递归处理子步骤
        if step.type == 'condition':
            # 处理条件为真的子步骤
            true_steps = step_data.get('config', {}).get('true_steps', [])
            create_steps(scene_id, true_steps, step.id, 0)
            
            # 处理条件为假的子步骤
            false_steps = step_data.get('config', {}).get('false_steps', [])
            create_steps(scene_id, false_steps, step.id, len(true_steps))
        
        elif step.type == 'loop':
            # 处理循环体子步骤
            body_steps = step_data.get('config', {}).get('body_steps', [])
            create_steps(scene_id, body_steps, step.id, 0)